import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:app_30/models/img_entity.dart';
import 'package:app_30/models/load_entity.dart';
import 'package:app_30/models/vip_entity.dart';
import 'package:app_30/net/dio_utils.dart';
import 'package:app_30/net/http_api.dart';
import 'package:app_30/util/cache_utils.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/widgets.dart';

class HomeViewModel extends ChangeNotifier {
  Uint8List? bytes;
  LoadEntity? loadData;
  VipEntity? vipData;

  String assetImg = "assets/image/empty.png";
  List<String> data = [];
  bool isStart = false;
  int stepCount = 1;
  double addMoney = 0.0;
  double allMoney = 0.0;
  String errString = '';

  void initialise() {
    loadData = getLoadData();
    vipData = getVipData();
    allMoney = double.parse(getmoney()!);
    notifyListeners();
  }

  void change() {
    print('${isStart}');
    isStart = !isStart;
    if (isStart) {
      start();
    } else {
      stop();
    }
    notifyListeners();
  }

  void start() {
    stepCount = 1;
    next();
  }

  void stop() {
    data.clear();
    bytes = null;
    data.add('结束运行');
    assetImg = "assets/image/empty.png";
    notifyListeners();
  }

  void next() {
    if (!isStart) {
      return;
    } else if (stepCount == 0) {
      data.clear();
      bytes = null;
      data.add('请连接网络后使用!');
      stepCount = 1;
      nextString();
    } else if (stepCount == 1) {
      data.clear();
      bytes = null;
      assetImg = "assets/image/load2.gif";
      data.add('欢迎回来...');
      stepCount = 2;
      nextString();
    } else if (stepCount == 2) {
      data.add('正在进入淘联盟平台...');
      stepCount = 3;
      nextString();
    } else if (stepCount == 3) {
      data.add('正在为您搜索店家发布的佣金任务中...');
      stepCount = 31;
      nextString();
    } else if (stepCount == 31) {
      getImg();
    } else if (stepCount == 4) {
      data.add('接单成功，正在浏览佣金任务，并准备完成中');
      stepCount = 5;
      nextString();
    } else if (stepCount == 5) {
      data.add('正在为店家提高权重和人气排名中...');
      stepCount = 51;
      nextString();
    } else if (stepCount == 51) {
      //// 开始计算
      eranMoney();
    } else if (stepCount == 6) {
      stop();
      data.add(' 系统正在准备重新接单!');
      stepCount = 1;
      next();
    } else if (stepCount == 8) {
      if (loadData!.vip == "0") {
        data.add('今天赚取的收益以达上限，请您明天再来操作赚钱。。');
      } else {
        data.add('收益以满${vipData!.dayje},今天赚取的佣金以达上限，请您明天再来操作赚钱。');
      }
    } else if (stepCount == 9) {
      data.add('系统正在准备重新接单!');
      stepCount = 1;
      nextString();
    } else if (stepCount == 10) {
      data.add(
          '任务完成！商家可能会提高一些销量，商家托管给我们的佣金已打入您的余额中，本次您赚取到${addMoney.toStringAsFixed(2)}元钱');
      stepCount = 9;
      bytes = null;
      nextString();
    } else if (stepCount == 101) {
      stop();
      data.add('${errString}');
      isStart = !isStart;
      notifyListeners();
    } else {}
    showNotification();
  }

  void showNotification() {
    String title = 'App 停止运行';
    if (isStart) {
      title = '正在为您工作赚钱中...';
    }
    AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 10,
        channelKey: 'basic_channel',
        title: '${title}',
        body: '${getTitle()}',
        autoCancel: false,
        showWhen: true,
        displayOnForeground: true,
        displayOnBackground: true,
        locked: true,
      ),
    );
  }

  String getTitle() {
    String title = "";
    switch (stepCount) {
      case 0:
        title = '请连接网络后使用!';
        break;
      case 1:
        title = '欢迎回来...';
        break;
      case 2:
        title = '正在进入淘联盟平台...';
        break;
      case 3:
      case 31:
        title = '正在为您搜索店家发布的佣金任务中...';
        break;
      case 4:
        title = '接单成功，正在浏览佣金任务，并准备完成中';
        break;
      case 5:
      case 51:
        title = '正在为店家提高权重和人气排名中...';
        break;
      case 6:
        title = '系统正在准备重新接单!';
        break;
      case 8:
        if (loadData!.vip == "0") {
          title = '今天赚取的收益以达上限，请您明天再来操作赚钱。。';
        } else {
          title = '收益以满${vipData!.dayje},今天赚取的佣金以达上限，请您明天再来操作赚钱。';
        }
        break;
      case 9:
        title = '本轮任务已完成，正在准备重新接单。';
        break;
      case 10:
        title =
            '任务完成！商家可能会提高一些销量，商家托管给我们的佣金已打入您的余额中，本次您赚取到${addMoney.toStringAsFixed(2)}元钱';
        break;
      case 101:
        title = '${errString}';
        break;
    }
    return title;
  }

  void nextString() {
    notifyListeners();
    new Future.delayed(Duration(seconds: 5), () {
      next();
    });
  }

  ///  有问题 shu ju bu quan
  getImg() async {
    Map<String, dynamic> map = Map();
    map['user'] = loadData?.user;
    map['time'] = "";
    map['app'] = getPlatform();

    await DioUtils.instance.requestNetwork<List<ImgEntity>>(
      Method.post,
      HttpApi.getimg,
      params: map,
      onSuccess: (data) {
        if (data == null) {
          if (isStart) {
            stepCount = 6;
            next();
          }
        } else {
          // 开始展示图片
          bytes = Base64Decoder().convert(data[0].img!);
          stepCount = 4;
          next();
        }
      },
      onError: (_, __) {
        stepCount = 6;
        next();
      },
    );
  }

  eranMoney() async {
    addMoney = Random().nextDouble() *
            (double.parse(vipData!.maxje!) - double.parse(vipData!.minje!)) +
        double.parse(vipData!.minje!);
    allMoney = addMoney + allMoney;
    Map<String, dynamic> map = Map();
    map['user'] = "${loadData!.user}";
    map['mysqlid'] = "${loadData!.user}";
    map['jine'] = "${allMoney.toStringAsFixed(2)}";
    map['dayje'] = "${vipData!.dayje}";
    map['time'] = "";

    await DioUtils.instance.requestNetwork<String>(
      Method.post,
      HttpApi.jine,
      params: map,
      onSuccess: (data) {
        setmoney(allMoney.toStringAsFixed(2));
        stepCount = 10;
        next();
      },
      onError: (_, __) {
        stepCount = 101;
        errString = '${__}';
        next();
      },
    );
  }
}
